package libs

import (
	"encoding/json"
	"net/http"
	"time"
)

func UploadApiHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Headers", "Content-Type")
	w.Header().Set("content-type", "application/json")
	//w.Header().Set("content-type", "text/html")
	switch r.Method {
	case "GET":
		query := r.URL.Query()
		act := query["act"][0]
		md5List := query["md5"]
		md5Str := map[string]string{}
		switch act {
		case "get":
			if md5List == nil {
				return
			} else {
				for _, key := range md5List {
					value, err := RedisGetSet(key)
					if err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
						return
					}
					if len(value) > 0 {
						md5Str[key] = "1"
					} else {
						md5Str[key] = "0"
					}
				}
				jsonStr, _ := json.Marshal(md5Str)
				w.WriteHeader(200)
				w.Write([]byte(jsonStr))
			}
		case "set":
			//申请分支ID
			if md5List == nil {
				md5Str["num"] = "0"
			} else {
				for _, key := range md5List {
					RegKeyId, err := RegKeyId(key)
					if err != nil {
						http.Error(w, err.Error(), http.StatusInternalServerError)
						return
					}
					md5Str[key] = RegKeyId
				}
				jsonStr, _ := json.Marshal(md5Str)
				w.WriteHeader(200)
				w.Write([]byte(jsonStr))
			}
		}
	default:
		w.WriteHeader(http.StatusMethodNotAllowed)
	}
}

func RegKeyId(key string) (id string, err error) {
	//生成ID
	t := time.Now().UnixNano()
	//RedisSetStr()
	//RedisSetSet()
	id = EncodeId(t)
	return id, err
}
